package com.soulapp.hook.hooker

import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.highcapable.kavaref.KavaRef.Companion.resolve
import com.highcapable.kavaref.condition.type.Modifiers
import com.highcapable.kavaref.condition.type.VagueType
import com.highcapable.yukihookapi.hook.core.YukiMemberHookCreator.MemberHookCreator.Result
import com.highcapable.yukihookapi.hook.factory.applyModuleTheme
import com.highcapable.yukihookapi.hook.log.YLog
import com.soulapp.data.ConfigData
import com.soulapp.hook.R
import com.soulapp.hook.databinding.DialogInputFollowBinding

// 自定义关注被关注数(本地)
object FollowHook : BaseHooker() {
    private const val TAG = "FollowHook"
    private var hook: Result? = null

    override fun getKey() = ConfigData.follow

    override fun onHook() {
        startHook()
    }

    override fun startHook() {
        YLog.debug("startHook $TAG $hookEnabled")
        if (!hookEnabled) return

        "cn.soulapp.android.component.home.me.UserHomeHeaderHelper".toClass()
            .resolve()
            .optional()
            .method {
                modifiers(Modifiers.PRIVATE, Modifiers.FINAL)
                name("A")
                parameters(Context::class)
                returnType == Void::class.javaPrimitiveType
            }.first()
            .hook {
                YLog.debug("hook $TAG hook")
                after {
                    YLog.debug("hook $TAG after")

                    // 关注数量
                    val followNumField = instance.javaClass.getDeclaredField("j")
                    followNumField.isAccessible = true
                    val followNum = followNumField.get(instance) as? TextView
                    followNum?.addTextChangedListener(object : TextWatcher {
                        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
                            followNumChangeText(followNum, this)
                        }

                        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}

                        override fun afterTextChanged(editable: Editable) {
                            followNumChangeText(followNum, this)
                        }
                    })

                    // 被关注数量
                    val followedNumField = instance.javaClass.getDeclaredField("l")
                    followedNumField.isAccessible = true
                    val followedNum = followedNumField.get(instance) as? TextView
                    followedNum?.addTextChangedListener(object : TextWatcher {
                        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
                            followedNumChangeText(followedNum, this)
                        }

                        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}

                        override fun afterTextChanged(editable: Editable) {
                            followedNumChangeText(followedNum, this)
                        }
                    })
                }
            }

    }

    private fun followNumChangeText(followedNum: TextView, textWatcher: TextWatcher) {
        followedNum.removeTextChangedListener(textWatcher)
        followedNum.text = ConfigData.getString(ConfigData.followNum, "")
        followedNum.addTextChangedListener(textWatcher)
    }

    private fun followedNumChangeText(followNum: TextView, textWatcher: TextWatcher) {
        followNum.removeTextChangedListener(textWatcher)
        followNum.text = ConfigData.getString(ConfigData.followedNum, "")
        followNum.addTextChangedListener(textWatcher)
    }

    private fun showFollowDialog(context: Context) {
        val themedContext = context.applyModuleTheme(R.style.AppTheme)
        val binding = DialogInputFollowBinding.inflate(LayoutInflater.from(themedContext))
        val dialogView = binding.root

        val followNumEditText = binding.followNumEditText

        followNumEditText.apply {
            setText(ConfigData.getString(ConfigData.followNum, "0"))
        }
        val followedNumEditText = binding.followedNumEditText
        followedNumEditText.apply {
            setText(ConfigData.getString(ConfigData.followedNum, "0"))
        }

        val alertDialog = MaterialAlertDialogBuilder(themedContext)
        alertDialog.setTitle("设置数量")
        alertDialog.setView(dialogView)

        alertDialog.setPositiveButton("确定") { dialog, _ ->
            // 收起输入法键盘
            hideKeyboard(dialogView, context)

            val followNum = followNumEditText.text.toString()
            val followedNum = followedNumEditText.text.toString()

            ConfigData.putString(ConfigData.followNum, followNum)
            ConfigData.putString(ConfigData.followedNum, followedNum)
            Toast.makeText(context, "关注数量：${followNum}，被关注数量：${followedNum}", Toast.LENGTH_SHORT).show()
            dialog.dismiss()
        }
        alertDialog.setNegativeButton("取消") { dialog, _ ->
            // 收起输入法键盘
            hideKeyboard(dialogView, context)
            dialog.dismiss()
        }
        alertDialog.show()
    }

    // 收起输入法键盘
    private fun hideKeyboard(view: View, context: Context) {
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
    }

    // 显示输入法键盘
    private fun showKeyboard(editText: EditText, context: Context) {
        editText.requestFocus()
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT)
    }

    private fun testHook(className: String) {
        val invoke = className.toClass()
            .resolve()
            .optional()
            .method {
                modifiers(Modifiers.PUBLIC, Modifiers.STATIC)
                name("c")
                parameters(Int::class.java, VagueType)
            }.first()
            .invoke(1, null)

        YLog.debug("invoke AutoUpdate 结果: $invoke")
    }

    // 重写clickListener属性并赋值
    override var clickListener: ((context: Context) -> Unit)? = { context ->
        showFollowDialog(context)
    }

    override fun stopHook() {
        if (!hookEnabled) return

        hook?.let {
            it.remove {
                YLog.debug("stopHook $TAG 成功")
            }
        } ?: YLog.debug("stopHook $TAG 失败")

        hookEnabled = false
    }

}